﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure.ServiceRuntime;
using WebRole1.Search.Query;

namespace Microsoft.WindowsAzure.Search
{
    public class IndexParser
    {
        public static Dictionary<String, Entry> Parse(CloudBlob blob, List<String> queryTerms)
        {
            Dictionary<String, Entry> dictionary = new Dictionary<String, Entry>();

            String content = blob.DownloadText();

            String[] lines = Tokenizer.LineTokenize(content);
            String line;

            // get index for query terms from index file
            for (int k = 0; k < lines.Length && dictionary.Keys.Count < queryTerms.Count; k++)
            {
                line = lines[k];
                String[] indexLine = Tokenizer.CommaTokenize(line);
                if (queryTerms.Contains(indexLine[0]))
                {
                    String term = indexLine[0];
                    int docFreq = Convert.ToInt32(indexLine[1]);
                    List<Posting> posting_list = new List<Posting>();
                    for (int i = 2; i < indexLine.Length; i += 2)
                    {
                        Posting posting = new Posting(Convert.ToInt32(indexLine[i]), Convert.ToInt32(indexLine[i + 1]));
                        posting_list.Add(posting);
                    }
                    Entry entry = new Entry(docFreq, posting_list);
                    dictionary.Add(term, entry);
                }
            }
            return dictionary;
        }
    }
}